<?php

namespace App\Models;

use App\Http\Common\Lib\Common;
use Illuminate\Database\Eloquent\Model;

class User extends BaseModel
{
	//
	protected $validatorName = 'User';

	/**
	 * 推荐记录
	 * @return \Illuminate\Database\Eloquent\Relations\HasMany
	 */
	public function lotteryRecords()
	{
		return $this->hasMany('App\Models\LotteryRecord', 'user_id', 'id');
	}

	/**
	 * 积分2位小数
	 * @param $value
	 * @return float
	 */
	public function getScoreAttribute($value)
	{
		return round($value, 2);
	}

	public function add($input)
	{
		$scene = 'add2';
		if (isset($input['password']) && $input['password']) {
			$scene = 'add';
		}
		$validateRes = $this->validateData($input, $scene);
		if ($validateRes['status'] != config('statusInfo.status.success')) {
			return Common::dataFormat($validateRes['status'], $validateRes['msg']);
		}
		$isUnique = $this->checkUnique('account', $input['account'], [['status', '>', -1]]);
		if (!$isUnique) {
			return Common::dataFormat(config('statusInfo.status.repeated'), '该账号已存在');
		}
		$input['salt'] = Common::randomString(6);
		if (!isset($input['password']) || !$input['password']) {
			$input['password'] = '123456';
		}
		$input['password'] = $this->encryptPwd($input['password'], $input['salt']);
		$user = new User();
		$user->setData($input);
		$res = $user->save();
		if ($res) {
			return Common::dataFormat(config('statusInfo.status.success'), config('statusInfo.msg.success'), [$this->primaryKey => $user->id]);
		} else {
			return Common::dataFormat(config('statusInfo.status.fail'), config('statusInfo.msg.fail'));
		}
	}

	public function edit($input)
	{
		$scene = 'edit2';
		if (isset($input['password']) && $input['password']) {
			$scene = 'edit';
		}
		$validateRes = $this->validateData($input, $scene);
		if ($validateRes['status'] != config('statusInfo.status.success')) {
			return Common::dataFormat($validateRes['status'], $validateRes['msg']);
		}
		$user = $this->where($this->primaryKey, $input[$this->primaryKey])->where('status', '>', -1)->first();
		if (!$user) {
			return Common::dataFormat(config('statusInfo.status.notFound'), config('statusInfo.msg.notFound'));
		}
		if (isset($input['password']) && $input['password']) {
			$input['password'] = $this->encryptPwd($input['password'], $user->salt);
		} else {
			unset($input['password']);
		}
		$user->setData($input);
		$res = $user->save();
		if ($res) {
			return Common::dataFormat(config('statusInfo.status.success'), config('statusInfo.msg.success'));
		} else {
			return Common::dataFormat(config('statusInfo.status.fail'), config('statusInfo.msg.fail'));
		}
	}

	/**
	 * 详情
	 * @param $id
	 * @return array
	 */
	public function detail($id)
	{
		$user = $this->where($this->primaryKey, $id)->where('status', '>', -1)->first();
		if (!$user) {
			return Common::dataFormat(config('statusInfo.status.notFound'), config('statusInfo.msg.notFound'));
		}
		unset($user->salt);
		unset($user->password);
		return Common::dataFormat(config('statusInfo.status.success'), config('statusInfo.msg.success'), $user);
	}

	/**
	 * 挑选用户
	 * @param string $session
	 * @param int $rate
	 * @param int $number
	 * @param string $type
	 * @param bool $isGreat
	 * @return mixed
	 */
	public function pickUsers($session = '', $rate = 60, $number = 10, $score = 0, $type = 'month', $isGreat = true)
	{
		if (!$session) {
			$session = date('Ymd');
		}
		$type = strtolower($type);
		$endTime = strtotime($session);
		switch ($type) {
			case 'week':
				$startTime = $endTime - 3600 * 24 * 7;
				break;
			case 'month':
				$startTime = $endTime - 3600 * 24 * 30;
				break;
			case 'quarter':
				$startTime = $endTime - 3600 * 24 * 90;
				break;
			default:
				$startTime = $endTime - 3600 * 24 * 30;
				break;
		}
		$start = date('Ymd', $startTime - 1);

		$pickUsers = [];
		$recordModel = new LotteryRecord();
		$this->where('status', 1)
			->select(['id', 'account', 'nickname', 'email', 'phone', 'sex', 'score', 'status'])
			->orderBy('score', 'desc')
			->chunk(100, function ($users) use (&$pickUsers, $recordModel, $start, $endTime, $type, $number, $score, $isGreat, $rate) {
				foreach ($users as $key => $user) {
					$info = $recordModel->statistic($user->id, $start, date('Ymd', $endTime - 1), $type);
					$getScore = number_format($info->total_odds - $info->pay_scores, 2);
					if ($info->total_number < $number) {
						unset($users[$key]);
						continue;
					}
					if ($isGreat) {
						//挑选命中率高的用户
						if (($info->rate < $rate) || ($getScore < $score)) {
							unset($users[$key]);
							continue;
						}
					} else {
						//挑选命中率低的用户
						if (($info->rate > $rate) || ($getScore > $score)) {
							unset($users[$key]);
							continue;
						}
					}
					$pickUsers[] = $user;
				}
				unset($users);
			});
		$pickUsers = collect($pickUsers);
		return $pickUsers;


		/*$users = $this->where('status', 1)
			->select(['id', 'account', 'nickname', 'email', 'phone', 'sex', 'score', 'status'])
			->orderBy('score', 'desc')
			->get();

		foreach ($users as $key => $user) {
			$info = $recordModel->statistic($user->id, $start, date('Ymd',$endTime-1), $type);
			$getScore = number_format($info->total_odds - $info->pay_scores, 2);
			if ($info->total_number < $number) {
				unset($users[$key]);
				continue;
			}
			if ($isGreat) {
				//挑选命中率高的用户
				if (($info->rate < $rate) || ($getScore < $score)) {
					unset($users[$key]);
					continue;
				}
			} else {
				//挑选命中率低的用户
				if (($info->rate > $rate) || ($getScore > $score)) {
					unset($users[$key]);
					continue;
				}
			}
		}
		return $users;*/
	}

	/**
	 * 加密密码
	 * @param $password
	 * @param $salt
	 * @return string
	 */
	private function encryptPwd($password, $salt)
	{
		return md5(md5($password) . $salt);
	}
}
